﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using System.Security.Principal;
using WaterRegimenMonitor.Web.Domain;

namespace WaterRegimenMonitor.Web
{
    /// <summary>
    /// 应用程序入口类。
    /// </summary>
    public class MvcApplication : System.Web.HttpApplication
    {
        /// <summary>
        /// 注册全局过滤器。
        /// </summary>
        /// <param name="filters">过滤器信息。</param>
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            //filters.Add(new HandleErrorAttribute());
        }

        /// <summary>
        /// 注册路由表。
        /// </summary>
        /// <param name="routes">路由信息。</param>
        public static void RegisterRoutes(RouteCollection routes)
        {
            //忽略资源访问
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            //注册登陆页面路由
            routes.MapRoute("Login", "Login", new { controller = "Login", action = "User", id = UrlParameter.Optional });

            //注册首页路由
            routes.MapRoute("Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional });
        }

        /// <summary>
        /// 处理应用程序启动事件。
        /// </summary>
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
        }

        /// <summary>
        /// 处理请求认证事件。
        /// </summary>
        /// <param name="sender">事件源。</param>
        /// <param name="e">包含事件参数的<see cref="System.EventArgs"/>对象。</param>
        /// <exception cref="System.Exception">web.config 文件设置错误!</exception>
        protected void Application_AuthenticateRequest(Object sender, EventArgs e)
        {
            if (HttpContext.Current.Request.IsAuthenticated)
            {
                IPrincipal principal = HttpContext.Current.User;
                if (principal != null && principal.Identity != null && (principal.Identity is FormsIdentity))
                {
                    Context.User = new UserPrincipal(principal.Identity, null);
                    System.Threading.Thread.CurrentPrincipal = Context.User;
                }
                else
                {
                    throw new Exception("web.config 文件设置错误!");
                }
            }
        }

        /// <summary>
        /// 处理开始请求事件。
        /// </summary>
        /// <param name="sender">事件源。</param>
        /// <param name="e">包含事件参数的<see cref="System.EventArgs"/>对象。</param>
        /// <remarks></remarks>
        /// <history>
        /// [zanezeng]               2012/03/09 10:13    创建
        /// </history>
        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            //更新认证Cookie的值。
            try
            {
                if (HttpContext.Current.Request.Form[SESSION_PARAM_NAME] != null)
                {
                    UpdateCookie(SESSION_COOKIE_NAME, HttpContext.Current.Request.Form[SESSION_PARAM_NAME]);
                }
                else if (HttpContext.Current.Request.QueryString[SESSION_PARAM_NAME] != null)
                {
                    UpdateCookie(SESSION_COOKIE_NAME, HttpContext.Current.Request.QueryString[SESSION_PARAM_NAME]);
                }
            }
            catch (Exception)
            {
            }

            //更新认证编号
            try
            {
                //获得窗体认证Cookie名称
                string auth_cookie_name = FormsAuthentication.FormsCookieName;

                //更新认证Cookie
                if (HttpContext.Current.Request.Form[AUTH_PARAM_NAME] != null)
                {
                    UpdateCookie(auth_cookie_name, HttpContext.Current.Request.Form[AUTH_PARAM_NAME]);
                }
                else if (HttpContext.Current.Request.QueryString[AUTH_PARAM_NAME] != null)
                {
                    UpdateCookie(auth_cookie_name, HttpContext.Current.Request.QueryString[AUTH_PARAM_NAME]);
                }
            }
            catch
            {
            }
        }

        #region ---Private Method

        /// <summary>
        /// 更新Cookie。
        /// </summary>
        /// <param name="cookie_name">Cookie的名称。</param>
        /// <param name="cookie_value">Cookie的值。</param>
        /// <remarks></remarks>
        /// <history>
        /// [zanezeng]               2012/03/09 10:14    创建
        /// </history>
        private void UpdateCookie(string cookie_name, string cookie_value)
        {
            //获得Cookie
            HttpCookie cookie = HttpContext.Current.Request.Cookies.Get(cookie_name);

            //判定指定的Cookie是否存在
            if (null == cookie)
            {
                //如果不存在，则创建
                cookie = new HttpCookie(cookie_name);
            }

            //设置Cookie的值
            cookie.Value = cookie_value;

            //更新Cookie
            HttpContext.Current.Request.Cookies.Set(cookie);
        }

        #endregion

        #region ---Const

        /// <summary>
        /// 会话编号参数名称。
        /// </summary>
        /// <remarks></remarks>
        /// <history>
        /// [zanezeng]               2012/03/09 10:16    创建
        /// </history>
        private const string SESSION_PARAM_NAME = "ASPSESSID";

        /// <summary>
        /// 会话Cookie名称
        /// </summary>
        /// <remarks></remarks>
        /// <history>
        /// [zanezeng]               2012/03/09 10:16    创建
        /// </history>
        private const string SESSION_COOKIE_NAME = "ASP.NET_SESSIONID";

        /// <summary>
        /// 认证编号参数名称
        /// </summary>
        /// <remarks></remarks>
        /// <history>
        /// [zanezeng]               2012/03/09 10:18    创建
        /// </history>
        private const string AUTH_PARAM_NAME = "AUTHID";

        #endregion
    }
}